<template>
	<view class="page" v-if="detailData.info.files.length">
		<view class="preview-box" :class="{'hasMovie': canMakeMovie}">
			<!-- 主图预览区 -->
			<swiper class="preview-swiper" :class="{'hasMovie': canMakeMovie}" :current="currentIndex" @change="handleSwiperChange">
				<swiper-item v-for="(item, index) in detailData.info.files" :key="index">
					<view class="img-wrapper" :class="{'hasMovie': canMakeMovie}">
						<video v-if="item.ext.includes('mp4')" :src="item.url" class="video" :class="{'hasMovie': canMakeMovie}" object-fit="fill"></video>
						<view v-else class="preview-image" :class="{'hasMovie': canMakeMovie}" :style="{ 'backgroundImage': 'url(' + item.url + '?style=imageMogr2/thumbnail/1200x)' }"></view>
					</view>
				</swiper-item>
			</swiper>
			<view class="ai-text">*该功能由AI生成、人工智能生成</view>
		</view>
		<!-- 全图片并且套系存在movieUrl-->
		<view class="movie-btn" v-if="canMakeMovie">
			<up-button color="#E7B796" :text="`当前照片生成视频(${detailData.info.photo.moviePrice / 100}元)`" @click="makeMovie"></up-button>
		</view>
		<!-- 底部缩略图区 -->
		<scroll-view class="gallery-scroll" scroll-x>
		  <view class="gallery-content">
		    <view class="gallery-item" v-for="(item, index) in detailData.info.files" :key="index" :class="{ active: currentIndex === index }" @click="handleThumbnailTap(index)">
				<view v-if="item.ext.includes('mp4')" class="video">
					<video :src="item.url" class="video" :controls="false" :show-center-play-btn="false" object-fit="fill"></video>
					<up-icon name="play-right-fill" color="#ffffff" size="20" class="play"></up-icon>
				</view>
				<view v-else class="gallery-image" :style="{ 'backgroundImage': 'url(' + item.url + '?style=imageMogr2/thumbnail/1200x)' }"></view>
			</view>
		  </view>
		</scroll-view>
		<view class="btn-box">
			<button class="up-reset-button kefu-btn" open-type="contact" v-if="['1', '2'].includes(detailData.info.feedStatus)">
				<img src="https://gamumu.hilumo.com/prod-api/files/down/1963082541930688512.png" alt="客服" class="kefu-icon">
				<view class="kefu-text">客服</view>
			</button>
			<button class="up-reset-button kefu-btn" v-if="['0'].includes(detailData.info.feedStatus)" @click="toFeedPage">
				<img src="https://gamumu.hilumo.com/prod-api/files/down/1963082541930688512.png" alt="客服" class="kefu-icon">
				<view class="kefu-text">客服</view>
			</button>
			<button class="download-button" type="primary" @click="handleDownload">下 载</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed
	} from 'vue';
	
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	
	
	const detailData = reactive({
		info: {
			files: [],
			photo: {}
		}
	})
	
	onLoad((option) => {
		detailData.info.uuid = option.uuid
	})
	
	onShow(() => {
		getOrderData()
	})
	
	const canMakeMovie = computed(() => {
		const { type, movieUrl } = detailData.info
		return type == 0 && movieUrl
	})
	
	// 获取订单详情
	function getOrderData() {
		const token = uni.getStorageSync('token')
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/system/pays/${detailData.info.uuid}`,
			method: 'GET',
			header: {
				'Authorization': "Bearer " + token,
			},
			success: (res) => {
				if (res.data.code === 200) {
					detailData.info = res.data.data
				} else {
					uni.showToast({
						icon: 'none',
						title: '系统开小差了'
					})
				}
			},
			fail: (error) => {
				uni.showToast({
					icon: 'none',
					title: '系统开小差了'
				})
			}
		});
	}

	const currentIndex = ref(0);

	const handleSwiperChange = (e) => {
		currentIndex.value = e.detail.current;
	};

	const handleThumbnailTap = (index) => {
		currentIndex.value = index;
	};

	const handleDownload = () => {
		uni.getSetting({
			success: function(res) {
				const type = detailData.info.files[currentIndex.value].ext
				if (res.authSetting['scope.writePhotosAlbum']) { // 用户授权相册权限
					if (type.includes('mp4')) {
						saveVideo()
					} else {
						saveImg()
					}
				} else { // 用户没有授权相册权限
					uni.showModal({
						title: '提示',
						content: '用户未授权相册权限，点击授权',
						success: function (res) {
							if (res.confirm) {
								 uni.authorize({
									scope: 'scope.writePhotosAlbum',
									success: () => {
										if (type.includes('mp4')) {
											saveVideo()
										} else {
											saveImg()
										}
									},
									fail: () => { // 用户拒绝授权，引导手动开启
									  uni.showModal({
											title: '提示',
											content: '需授权相册权限才能保存图片',
											success: (res) => {
											  if (res.confirm) uni.openSetting();
											}
									  });
								  }	,
								})
							} else {
								uni.showToast({
								  title: "用户取消授权，不能使用下载功能",
								  icon: "error",
								})
							}
						},
					})
				}
			},
			fail: function(error) {
				uni.showToast({
				  title: "查询授权失败",
				  icon: "error",
				})
			}
		})
	};
	// 视频保存到相册
	function saveVideo() {
		uni.showLoading({
			title: '正在保存'
		})
		uni.downloadFile({
			url: detailData.info.files[currentIndex.value].url,
			filePath: uni.env.USER_DATA_PATH + '/' + Date.now() + detailData.info.files[currentIndex.value].ext,
			success: (response) => {
				uni.saveVideoToPhotosAlbum({
					filePath: response.filePath,
					success: res => {
						uni.showToast({title: "保存成功",icon: "success"})
					},
					fail: err => {
						uni.showToast({title: "保存失败",icon: "error"})
					}
				});
			}
		})
	}
	
	// 图片保存到相册
	function saveImg() {
		uni.showLoading({
			title: '正在保存'
		})
		uni.downloadFile({
		  url: detailData.info.files[currentIndex.value].url,
		  header:{
		    responseType: 'arraybuffer',
		    Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
		  },
		  filePath: uni.env.USER_DATA_PATH + '/' + Date.now() + detailData.info.files[currentIndex.value].ext,
		  success:(response)=>{
			uni.saveImageToPhotosAlbum({
				filePath: response.filePath,
				success: res => {
					uni.showToast({title: "保存成功",icon: "success"})
				},
				fail: err => {
					uni.showToast({title: "保存失败",icon: "error"})
				}
			});
		  },
		  fail:(errr)=>{
			uni.showToast({
				icon: 'none',
				title: '系统开小差了'
			})
		  }
		})
	}
	
	// 制作视频
	function makeMovie() {
		const { photoId, frontUrl, shape } = detailData.info
		const selectImg = detailData.info.files[currentIndex.value]
		const token = uni.getStorageSync('token')
		const params = {
			photoId,
			frontUrl,
			shape,
			type: 2,
			fileId: selectImg.uuid
		}
		// 处理提交逻辑
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/pay/wx`,
			method: 'POST',
			header: {
				'Authorization': "Bearer " + token,
			},
			data: params,
			success: (res) => {
				if (res.data.code === 200) {
					const { free, paySign, photoPay } = res.data
					if (free === '0') {
						// 微信支付
						const orderId = JSON.parse(res.data.pay.att).photoPayId
						const { timeStamp, nonceStr, signType, sign } = paySign
						wx.requestPayment({
							timeStamp,
							nonceStr,
							package: paySign.package,
							signType,
							paySign: sign,
							success(sres) {
								markingFn(orderId)
							},
							fail (sres) {
								uni.showToast({
									icon: 'error',
									title: '支付失败'
								})
							}
						})
					} else {
						// 免费不需要支付
						const orderId = photoPay.uuid
						markingFn(orderId)
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: '系统开小差了'
					})
				}
			},
			fail: (error) => {
				uni.showToast({
					icon: 'none',
					title: '系统开小差了'
				})
			}
		});
	}
	
	function markingFn(orderId) {
		uni.showToast({
			title: '制作中',
			icon: 'loading',
			duration: 1500
		});
		setTimeout(() => {
			uni.showModal({
				content: '制作时间大约几分钟，5s后自动为您跳转订单详情',
				cancelText: '继续制作',
				confirmText: '订单详情',
				cancelColor: '#D19973',
				confirmColor: '#D19973',
				success: function (sres) {
					if (sres.confirm) {
						uni.navigateTo({
							url: `/pages/order/detail?uuid=${orderId}`
						})
					} else if (sres.cancel) {
						uni.navigateTo({
							url: '/pages/filter/filter?age=0&category=0'
						})
					}
				}
			})
		}, 1500)
		setTimeout(() => {
			uni.hideModal()
			uni.navigateTo({
				url: `/pages/order/detail?uuid=${orderId}`
			})
		}, 5000)
	}
	
	// 去反馈
	function toFeedPage() {
		uni.navigateTo({
			url: `/pages/feed/feed?orderId=${detailData.info.uuid}&photoId=${detailData.info.photoId}`
		})
	}
</script>

<style lang="scss" scoped>
	.preview-box {
		height: 1000rpx;
		box-sizing: border-box;
	}
	.page {
		position: relative;
	}
	
	.preview-swiper {
		flex: 1;
		width: 100%;
		height: 960rpx;
	}
	.img-wrapper {
		width: 100%;
		height: 960rpx;
		overflow: hidden;
		.video {
			width: 100%;
			height: 960rpx;
		}
	}
	.preview-image {
		width: 100%;
		height: 960rpx;
		background-size: 100% auto;
		background-repeat: no-repeat;
		background-position: center;
	}
	
	.hasMovie {
		height: 860rpx;
	}
	.gallery-scroll {
	  width: 100%;
	  height: 254rpx;
	  overflow: auto;
	  padding: 0 40rpx;
	  box-sizing: border-box;
	  margin-bottom: 40rpx;
	}
	
	.gallery-content {
		margin-top: 20rpx;
		display: flex;
		gap: 10rpx;
	}
	
	.gallery-item {
	  flex-shrink: 0;
	  width: 160rpx;
	  height: 214rpx;
	  border-radius: 12rpx;
	  overflow: hidden;
	  position: relative;
	  transition: all 0.5s;
	  .video {
		width: 160rpx;
		height: 214rpx;
	  }
	  .play {
	  	position: absolute;
	  	top: 50%;
	  	left: 50%;
	  	margin-top: -20rpx;
	  	margin-left: -20rpx;
	  }
	}
	
	.gallery-image {
		width: 160rpx;
		height: 214rpx;
		background-size: 100% auto;
		background-repeat: no-repeat;
		background-position: center;
		display: flexbox;
	}
	
	.gallery-item.active::after {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		box-sizing: border-box;
		border-radius: 8rpx;
		border: 3px solid #D19973
	}
	.btn-box {
		padding: 0 40rpx 30rpx;
		overflow: hidden;
		.download-button {
			float: right;
			width: 510rpx;
			height: 100rpx;
			background: linear-gradient(90deg, #D19973 0%, #EBBD9D 100%);
			border-radius: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-style: Heavy;
			font-size: 36rpx;
			leading-trim: NONE;
			line-height: 100rpx;
			&:active {
				opacity: 0.8;
			}
		}
		.kefu-btn {
			float: left;
			width: 160rpx;
			padding-top: 5rpx;
			text-align: center;
			.kefu-icon {
				width: 48rpx;
				height: 48rpx;
				object-fit: contain;
			}
			.kefu-text {
				font-family: PingFang SC;
				font-weight: 500;
				font-style: Medium;
				font-size: 24rpx;
				leading-trim: NONE;
				line-height: 34rpx;
				letter-spacing: 0%;
				color: #D19973;
			}
		}
	}
	.movie-btn {
		margin: 30rpx auto 0;
		width: 670rpx;
		display: block;
	}
</style>